package com.black.platform.dictionary.web;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.black.common.vo.DictionaryTreeVo;
import com.black.common.web.ApiResponse;
import com.black.common.web.ApiResponseBuilder;
import com.black.common.web.PageQuery;
import com.black.platform.dictionary.po.Dictionary;
import com.black.platform.dictionary.service.handler.DictionaryHandlerService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("dictionary")
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class DictionaryController {

    private final DictionaryHandlerService dictionaryHandlerService;

    @PostMapping("search")
    public ApiResponse<IPage<DictionaryTreeVo>> search(@RequestBody PageQuery<Dictionary> searchVo) {
        return ApiResponseBuilder.ok(dictionaryHandlerService.search(searchVo));
    }

    @GetMapping("Id/{id}")
    public ApiResponse<Dictionary> getById(@PathVariable("id") Long id) {
        return ApiResponseBuilder.ok(dictionaryHandlerService.getById(id));
    }


    @PostMapping("save")
    public ApiResponse<Boolean> save(@RequestBody Dictionary dictionary) {
        return ApiResponseBuilder.ok(dictionaryHandlerService.save(dictionary));
    }

    @PostMapping("update")
    public ApiResponse<Boolean> saveOrUpdate(@RequestBody Dictionary dictionary) {
        return ApiResponseBuilder.ok(dictionaryHandlerService.update(dictionary));
    }

    @DeleteMapping
    public ApiResponse<String> delete(@RequestBody List<Long> ids) {

        if (dictionaryHandlerService.deleteByIds(ids)) {
            return ApiResponseBuilder.ok("删除成功");
        } else {
            return ApiResponseBuilder.error("删除失败");
        }
    }

    @GetMapping("allCodeType")
    public ApiResponse<List<DictionaryTreeVo>> allCodeType() {
        return ApiResponseBuilder.ok(dictionaryHandlerService.getAllCodeTypeTreeVo());
    }

    @GetMapping("{codeType}")
    public ApiResponse<List<Dictionary>> getByCodeType(@PathVariable("codeType") String codeType) {
        return ApiResponseBuilder.ok(dictionaryHandlerService.getByCodeType(codeType, false));
    }
}
